<template>
  <div class="menu-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>菜单管理</span>
          <div class="header-actions">
            <el-button type="success" @click="showOrderDialog">
              <el-icon><Sort /></el-icon>
              调整导航顺序
            </el-button>
            <el-button type="primary" @click="showAddDialog">
              <el-icon><Plus /></el-icon>
              添加菜单
            </el-button>
            <el-button type="success" @click="restoreCMDBMenus">
              <el-icon><Refresh /></el-icon>
              恢复CMDB菜单
            </el-button>
          </div>
        </div>
      </template>

      <!-- 菜单树表格 -->
      <el-table
        :data="menuTreeData"
        v-loading="loading"
        style="width: 100%"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        :default-expand-all="true"
        class="menu-tree-table"
      >
        <el-table-column label="菜单名称" min-width="250">
          <template #default="{ row }">
            <div class="menu-name-cell">
              <div class="menu-icon-wrapper">
                <el-icon v-if="row.icon" class="menu-icon">
                  <component :is="getIconComponent(row.icon)" />
                </el-icon>
                <el-icon v-else class="menu-icon placeholder-icon">
                  <Menu />
                </el-icon>
              </div>
              <div class="menu-info">
                <span class="menu-name" :class="{ 'parent-menu': !row.parent, 'child-menu': row.parent }">
                  {{ row.name }}
                </span>
                <div class="menu-tags">
                  <el-tag
                    v-if="!row.parent"
                    type="primary"
                    size="small"
                    class="level-tag"
                  >
                    一级菜单
                  </el-tag>
                  <el-tag
                    v-else
                    type="info"
                    size="small"
                    class="level-tag"
                  >
                    二级菜单
                  </el-tag>
                  <el-tag
                    v-if="row.children && row.children.length > 0"
                    type="success"
                    size="small"
                    class="children-count-tag"
                  >
                    {{ row.children.length }}个子菜单
                  </el-tag>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="路径" min-width="180">
          <template #default="{ row }">
            <el-text class="path-text" type="info">{{ row.path }}</el-text>
          </template>
        </el-table-column>
        <el-table-column prop="component" label="组件" min-width="150">
          <template #default="{ row }">
            <el-text v-if="row.component" class="component-text" type="warning">{{ row.component }}</el-text>
            <el-text v-else class="component-text" type="info">-</el-text>
          </template>
        </el-table-column>
        <el-table-column prop="sort_order" label="排序" width="80" align="center">
          <template #default="{ row }">
            <el-tag type="info" size="small">{{ row.sort_order }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="row.is_active ? 'success' : 'danger'" size="small">
              {{ row.is_active ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="权限" min-width="200">
          <template #default="{ row }">
            <div class="permissions-cell">
              <el-tag
                v-for="permission in row.permissions"
                :key="permission.id"
                type="info"
                size="small"
                class="permission-tag"
              >
                {{ permission.name }}
              </el-tag>
              <span v-if="!row.permissions || row.permissions.length === 0" class="no-permissions">
                无权限要求
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" align="center">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                type="primary"
                size="small"
                @click="showEditDialog(row)"
                :icon="Edit"
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="deleteMenu(row)"
                :icon="Delete"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑菜单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="menuForm"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="menuForm.name" />
        </el-form-item>
        <el-form-item label="菜单路径" prop="path">
          <el-input v-model="menuForm.path" />
        </el-form-item>
        <el-form-item label="组件路径" prop="component">
          <el-input v-model="menuForm.component" />
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <div class="icon-input-wrapper">
            <el-input
              v-model="menuForm.icon"
              placeholder="请选择或输入图标名称"
              class="icon-input"
            >
              <template #prepend>
                <el-icon v-if="menuForm.icon" class="icon-preview">
                  <component :is="getIconComponent(menuForm.icon)" />
                </el-icon>
                <el-icon v-else class="icon-preview placeholder">
                  <Menu />
                </el-icon>
              </template>
              <template #append>
                <el-button @click="showIconSelector" type="primary" size="small">
                  选择图标
                </el-button>
              </template>
            </el-input>
          </div>
        </el-form-item>
        <el-form-item label="父菜单" prop="parent">
          <el-select
            v-model="menuForm.parent"
            placeholder="留空创建一级菜单，选择父菜单创建二级菜单"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="menu in parentMenuOptions"
              :key="menu.id"
              :label="menu.name"
              :value="menu.id"
            />
          </el-select>
          <div style="font-size: 12px; color: #909399; margin-top: 4px;">
            提示：不选择父菜单将创建一级菜单，选择父菜单将创建二级菜单
          </div>
        </el-form-item>
        <el-form-item label="排序" prop="sort_order">
          <el-input-number v-model="menuForm.sort_order" :min="0" />
        </el-form-item>
        <el-form-item label="所需权限" prop="permission_ids">
          <el-select
            v-model="menuForm.permission_ids"
            multiple
            placeholder="请选择所需权限"
            style="width: 100%"
          >
            <el-option
              v-for="permission in permissionList"
              :key="permission.id"
              :label="permission.name"
              :value="permission.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="is_active">
          <el-switch v-model="menuForm.is_active" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 图标选择对话框 -->
    <el-dialog
      v-model="iconSelectorVisible"
      title="选择图标"
      width="800px"
      class="icon-selector-dialog"
    >
      <div class="icon-selector">
        <div class="icon-search">
          <el-input
            v-model="iconSearchKeyword"
            placeholder="搜索图标..."
            clearable
            @input="filterIcons"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>

        <div class="icon-categories">
          <el-tabs v-model="activeIconCategory" @tab-change="handleCategoryChange">
            <el-tab-pane label="常用图标" name="common">
              <div class="icon-grid">
                <div
                  v-for="icon in filteredCommonIcons"
                  :key="icon.name"
                  class="icon-item"
                  :class="{ active: menuForm.icon === icon.name }"
                  @click="selectIcon(icon.name)"
                >
                  <el-icon class="icon-display">
                    <component :is="getIconComponent(icon.name)" />
                  </el-icon>
                  <span class="icon-name">{{ icon.label }}</span>
                </div>
              </div>
            </el-tab-pane>

            <el-tab-pane label="系统图标" name="system">
              <div class="icon-grid">
                <div
                  v-for="icon in filteredSystemIcons"
                  :key="icon.name"
                  class="icon-item"
                  :class="{ active: menuForm.icon === icon.name }"
                  @click="selectIcon(icon.name)"
                >
                  <el-icon class="icon-display">
                    <component :is="getIconComponent(icon.name)" />
                  </el-icon>
                  <span class="icon-name">{{ icon.label }}</span>
                </div>
              </div>
            </el-tab-pane>

            <el-tab-pane label="业务图标" name="business">
              <div class="icon-grid">
                <div
                  v-for="icon in filteredBusinessIcons"
                  :key="icon.name"
                  class="icon-item"
                  :class="{ active: menuForm.icon === icon.name }"
                  @click="selectIcon(icon.name)"
                >
                  <el-icon class="icon-display">
                    <component :is="getIconComponent(icon.name)" />
                  </el-icon>
                  <span class="icon-name">{{ icon.label }}</span>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>

      <template #footer>
        <el-button @click="iconSelectorVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmIconSelection">确定</el-button>
      </template>
    </el-dialog>

    <!-- 智能图标推荐对话框 -->
    <el-dialog
      v-model="iconRecommendVisible"
      title="图标推荐"
      width="500px"
      class="icon-recommend-dialog"
    >
      <div class="icon-recommend">
        <div class="recommend-header">
          <el-icon class="recommend-icon"><MagicStick /></el-icon>
          <div class="recommend-text">
            <h4>智能图标推荐</h4>
            <p>根据菜单名称"{{ menuForm.name }}"，为您推荐以下图标：</p>
          </div>
        </div>

        <div class="recommended-icons">
          <div
            v-for="icon in recommendedIcons"
            :key="icon.name"
            class="recommended-icon-item"
            :class="{ selected: selectedRecommendIcon === icon.name }"
            @click="selectedRecommendIcon = icon.name"
          >
            <el-icon class="icon-display">
              <component :is="getIconComponent(icon.name)" />
            </el-icon>
            <div class="icon-info">
              <span class="icon-name">{{ icon.label }}</span>
              <span class="match-reason">{{ icon.reason }}</span>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <el-button @click="iconRecommendVisible = false">跳过</el-button>
        <el-button type="primary" @click="applyRecommendedIcon" :disabled="!selectedRecommendIcon">
          使用推荐图标
        </el-button>
      </template>
    </el-dialog>

    <!-- 导航顺序调整对话框 -->
    <el-dialog
      v-model="orderDialogVisible"
      width="900px"
      align-center
      @close="resetOrderDialog"
      class="order-dialog"
    >
      <template #header>
        <div class="dialog-header">
          <h3 class="dialog-title">
            <el-icon class="title-icon"><Sort /></el-icon>
            调整导航栏顺序
          </h3>
        </div>
      </template>

      <div class="order-management">
        <div class="order-tips">
          <div class="custom-alert">
            <div class="alert-icon">
              <el-icon><InfoFilled /></el-icon>
            </div>
            <div class="alert-content">
              <div class="alert-title">操作提示</div>
              <div class="alert-description">
                使用右侧的上下箭头按钮可以调整左侧导航栏的显示顺序，调整后点击保存生效
              </div>
            </div>
          </div>
        </div>

        <div class="order-content">
          <div class="order-list">
            <div class="section-header">
              <h4 class="section-title">
                <el-icon class="section-icon"><Menu /></el-icon>
                导航菜单顺序
              </h4>
              <div class="section-description">拖拽或使用箭头按钮调整菜单顺序</div>
            </div>
            <div class="menu-list">
              <draggable
                v-model="navigationOrder"
                item-key="path"
                class="draggable-list"
                ghost-class="ghost"
                chosen-class="chosen"
                drag-class="drag"
                :animation="200"
                handle=".drag-handle"
              >
                <template #item="{ element, index }">
                  <div
                    class="menu-item main-menu-item"
                    :class="{ 'has-children': element.children && element.children.length > 0 }"
                  >
                    <div class="menu-item-content">
                      <div class="menu-info">
                        <div class="drag-handle" title="拖拽排序">
                          <el-icon><Menu /></el-icon>
                        </div>
                        <div class="menu-level-indicator">
                          <div class="level-line"></div>
                        </div>
                        <el-icon class="menu-icon main-menu-icon">
                          <component :is="iconComponents[element.meta?.icon] || iconComponents.Menu" />
                        </el-icon>
                        <span class="menu-title main-menu-title">{{ element.meta?.title }}</span>
                        <el-tag v-if="element.children && element.children.length > 0" size="small" class="children-tag">
                          {{ element.children.length }} 个子菜单
                        </el-tag>
                        <el-button
                          v-if="element.children && element.children.length > 0"
                          size="small"
                          text
                          @click="toggleSubmenu(element.path)"
                          class="collapse-btn"
                        >
                          <el-icon>
                            <component :is="isSubmenuCollapsed(element.path) ? iconComponents.ArrowRight : iconComponents.ArrowDown" />
                          </el-icon>
                        </el-button>
                      </div>
                      <div class="menu-actions">
                        <span class="order-number main-order">{{ index + 1 }}</span>
                        <el-button
                          size="small"
                          type="primary"
                          :disabled="index === 0"
                          @click="moveUp(index)"
                          class="action-btn"
                        >
                          <el-icon><ArrowUp /></el-icon>
                        </el-button>
                        <el-button
                          size="small"
                          type="primary"
                          :disabled="index === navigationOrder.length - 1"
                          @click="moveDown(index)"
                          class="action-btn"
                        >
                          <el-icon><ArrowDown /></el-icon>
                        </el-button>
                      </div>
                    </div>

                    <!-- 子菜单 -->
                    <div
                      v-if="element.children && element.children.length > 0 && !isSubmenuCollapsed(element.path)"
                      class="submenu-list"
                    >
                      <div class="submenu-header">
                        <div class="submenu-title">子菜单</div>
                      </div>
                      <draggable
                        v-model="element.children"
                        item-key="path"
                        class="submenu-draggable"
                        ghost-class="submenu-ghost"
                        chosen-class="submenu-chosen"
                        drag-class="submenu-drag"
                        :animation="200"
                        handle=".submenu-drag-handle"
                      >
                        <template #item="{ element: child, index: childIndex }">
                          <div class="submenu-item">
                            <div class="submenu-content">
                              <div class="submenu-drag-handle" title="拖拽排序">
                                <el-icon><Menu /></el-icon>
                              </div>
                              <div class="submenu-level-indicator">
                                <div class="submenu-connector"></div>
                                <div class="submenu-dot"></div>
                              </div>
                              <div class="submenu-info">
                                <el-icon class="menu-icon submenu-icon">
                                  <component :is="child.meta?.icon || 'Menu'" />
                                </el-icon>
                                <span class="menu-title submenu-title">{{ child.meta?.title }}</span>
                              </div>
                              <div class="submenu-actions">
                                <span class="order-number sub-order">{{ childIndex + 1 }}</span>
                                <el-button
                                  size="small"
                                  type="info"
                                  :disabled="childIndex === 0"
                                  @click="moveSubMenuUp(index, childIndex)"
                                  class="action-btn sub-action-btn"
                                >
                                  <el-icon><ArrowUp /></el-icon>
                                </el-button>
                                <el-button
                                  size="small"
                                  type="info"
                                  :disabled="childIndex === element.children.length - 1"
                                  @click="moveSubMenuDown(index, childIndex)"
                                  class="action-btn sub-action-btn"
                                >
                                  <el-icon><ArrowDown /></el-icon>
                                </el-button>
                              </div>
                            </div>
                          </div>
                        </template>
                      </draggable>
                    </div>
                  </div>
                </template>
              </draggable>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <el-button @click="orderDialogVisible = false">取消</el-button>
        <el-button @click="resetNavigationOrder">重置顺序</el-button>
        <el-button type="primary" @click="saveNavigationOrder" :loading="saveOrderLoading">
          保存顺序
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, ElLoading, type FormInstance } from 'element-plus'
import {
  Plus, Sort, Menu, ArrowUp, ArrowDown, InfoFilled, ArrowRight,
  Edit, Delete, Search, MagicStick,
  // 常用图标
  Monitor, Setting, User, UserFilled, Key, Document,
  Box, Collection, Cpu, Coin, Connection, EditPen,
  Download, House, Files, Folder, FolderOpened,
  // 系统图标
  Tools, Bell, Lock, Unlock, View, Hide, Refresh, Upload,
  Share, Star, Flag, Calendar, Clock, Location,
  // 业务图标
  ShoppingCart, Goods, Money, CreditCard, Wallet, Shop,
  Van, Service, Phone, Message, ChatDotRound
} from '@element-plus/icons-vue'
import draggable from 'vuedraggable'
import api from '@/utils/api'

// 注册图标组件
const iconComponents = {
  Plus, Sort, Menu, ArrowUp, ArrowDown, InfoFilled, ArrowRight,
  Edit, Delete, Search, MagicStick,
  // 常用图标
  Monitor, Setting, User, UserFilled, Key, Document,
  Box, Collection, Cpu, Coin, Connection, EditPen,
  Download, House, Files, Folder, FolderOpened,
  // 系统图标
  Tools, Bell, Lock, Unlock, View, Hide, Refresh, Upload,
  Share, Star, Flag, Calendar, Clock, Location,
  // 业务图标
  ShoppingCart, Goods, Money, CreditCard, Wallet, Shop,
  Van, Service, Phone, Message, ChatDotRound
}

// 图标配置
const iconConfig = {
  common: [
    { name: 'Monitor', label: '监控' },
    { name: 'Setting', label: '设置' },
    { name: 'User', label: '用户' },
    { name: 'UserFilled', label: '用户(填充)' },
    { name: 'Key', label: '权限' },
    { name: 'Document', label: '文档' },
    { name: 'Box', label: '资产' },
    { name: 'Collection', label: '集合' },
    { name: 'Cpu', label: 'CPU' },
    { name: 'Coin', label: '数据库' },
    { name: 'Connection', label: '连接' },
    { name: 'EditPen', label: '编辑' },
    { name: 'Download', label: '下载' },
    { name: 'House', label: '首页' },
    { name: 'Files', label: '文件' },
    { name: 'Folder', label: '文件夹' },
    { name: 'FolderOpened', label: '打开文件夹' }
  ],
  system: [
    { name: 'Tools', label: '工具' },
    { name: 'Bell', label: '通知' },
    { name: 'Lock', label: '锁定' },
    { name: 'Unlock', label: '解锁' },
    { name: 'View', label: '查看' },
    { name: 'Hide', label: '隐藏' },
    { name: 'Refresh', label: '刷新' },
    { name: 'Upload', label: '上传' },
    { name: 'Share', label: '分享' },
    { name: 'Star', label: '收藏' },
    { name: 'Flag', label: '标记' },
    { name: 'Calendar', label: '日历' },
    { name: 'Clock', label: '时钟' },
    { name: 'Location', label: '位置' }
  ],
  business: [
    { name: 'ShoppingCart', label: '购物车' },
    { name: 'Goods', label: '商品' },
    { name: 'Money', label: '金钱' },
    { name: 'CreditCard', label: '信用卡' },
    { name: 'Wallet', label: '钱包' },
    { name: 'Shop', label: '商店' },
    { name: 'Van', label: '运输' },
    { name: 'Service', label: '服务' },
    { name: 'Phone', label: '电话' },
    { name: 'Message', label: '消息' },
    { name: 'ChatDotRound', label: '聊天' }
  ]
}

// 智能图标匹配规则
const iconMatchRules = [
  { keywords: ['仪表盘', '首页', '主页', 'dashboard', 'home'], icon: 'House', reason: '仪表盘相关' },
  { keywords: ['用户', '人员', 'user', 'people'], icon: 'User', reason: '用户管理相关' },
  { keywords: ['角色', 'role'], icon: 'UserFilled', reason: '角色管理相关' },
  { keywords: ['权限', '许可', 'permission', 'auth'], icon: 'Key', reason: '权限管理相关' },
  { keywords: ['菜单', 'menu', '导航'], icon: 'Menu', reason: '菜单导航相关' },
  { keywords: ['设置', '配置', 'setting', 'config'], icon: 'Setting', reason: '设置配置相关' },
  { keywords: ['监控', '监视', 'monitor', 'watch'], icon: 'Monitor', reason: '监控相关' },
  { keywords: ['文档', '文件', 'document', 'file'], icon: 'Document', reason: '文档文件相关' },
  { keywords: ['资产', '主机', 'asset', 'host', 'cmdb'], icon: 'Box', reason: '资产管理相关' },
  { keywords: ['数据库', 'database', 'db'], icon: 'Coin', reason: '数据库相关' },
  { keywords: ['日志', 'log'], icon: 'Document', reason: '日志相关' },
  { keywords: ['系统', 'system'], icon: 'Tools', reason: '系统相关' },
  { keywords: ['工具', 'tool'], icon: 'Tools', reason: '工具相关' },
  { keywords: ['图表', '报表', 'chart', 'report'], icon: 'Monitor', reason: '图表报表相关' }
]

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('添加菜单')
const isEdit = ref(false)
const editMenuId = ref(0)

// 图标选择相关
const iconSelectorVisible = ref(false)
const iconSearchKeyword = ref('')
const activeIconCategory = ref('common')
const filteredCommonIcons = ref(iconConfig.common)
const filteredSystemIcons = ref(iconConfig.system)
const filteredBusinessIcons = ref(iconConfig.business)

// 智能图标推荐相关
const iconRecommendVisible = ref(false)
const recommendedIcons = ref([])
const selectedRecommendIcon = ref('')

// 导航顺序管理相关
const orderDialogVisible = ref(false)
const saveOrderLoading = ref(false)
const navigationOrder = ref([])
const originalNavigationOrder = ref([])
const collapsedMenus = ref(new Set()) // 折叠的菜单集合

const menuList = ref([])
const permissionList = ref([])
const formRef = ref<FormInstance>()

// 计算属性：菜单树形数据
const menuTreeData = computed(() => {
  return buildMenuTree(menuList.value)
})

// 菜单表单
const menuForm = reactive({
  name: '',
  path: '',
  component: '',
  icon: '',
  parent: null,
  sort_order: 0,
  permission_ids: [],
  is_active: true
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' }
  ],
  path: [
    { required: true, message: '请输入菜单路径', trigger: 'blur' }
  ]
}

// 父菜单选项（只显示一级菜单，避免创建三级菜单）
const parentMenuOptions = computed(() => {
  return menuList.value.filter(menu => {
    // 排除当前编辑的菜单
    if (isEdit.value && menu.id === editMenuId.value) {
      return false
    }
    // 只返回一级菜单（没有父菜单的菜单）
    return !menu.parent
  }).map(menu => ({
    ...menu,
    name: menu.name + ' (一级菜单)'
  }))
})

// 工具函数：构建菜单树
const buildMenuTree = (menus: any[]) => {
  const menuMap = new Map()
  const rootMenus = []

  // 创建菜单映射
  menus.forEach(menu => {
    menuMap.set(menu.id, { ...menu, children: [] })
  })

  // 构建树形结构
  menus.forEach(menu => {
    const menuItem = menuMap.get(menu.id)
    if (menu.parent) {
      const parent = menuMap.get(menu.parent.id)
      if (parent) {
        parent.children.push(menuItem)
      }
    } else {
      rootMenus.push(menuItem)
    }
  })

  return rootMenus
}

// 工具函数：获取图标组件
const getIconComponent = (iconName: string) => {
  return iconComponents[iconName] || iconComponents.Menu
}

// 图标选择相关方法
const showIconSelector = () => {
  iconSelectorVisible.value = true
  resetIconFilter()
}

const selectIcon = (iconName: string) => {
  menuForm.icon = iconName
}

const confirmIconSelection = () => {
  iconSelectorVisible.value = false
}

const resetIconFilter = () => {
  iconSearchKeyword.value = ''
  filteredCommonIcons.value = iconConfig.common
  filteredSystemIcons.value = iconConfig.system
  filteredBusinessIcons.value = iconConfig.business
}

const filterIcons = () => {
  const keyword = iconSearchKeyword.value.toLowerCase()
  if (!keyword) {
    resetIconFilter()
    return
  }

  filteredCommonIcons.value = iconConfig.common.filter(icon =>
    icon.label.toLowerCase().includes(keyword) || icon.name.toLowerCase().includes(keyword)
  )
  filteredSystemIcons.value = iconConfig.system.filter(icon =>
    icon.label.toLowerCase().includes(keyword) || icon.name.toLowerCase().includes(keyword)
  )
  filteredBusinessIcons.value = iconConfig.business.filter(icon =>
    icon.label.toLowerCase().includes(keyword) || icon.name.toLowerCase().includes(keyword)
  )
}

const handleCategoryChange = () => {
  // 切换分类时重置搜索
  iconSearchKeyword.value = ''
  resetIconFilter()
}

// 智能图标推荐
const recommendIcon = (menuName: string) => {
  const recommendations = []
  const lowerMenuName = menuName.toLowerCase()

  iconMatchRules.forEach(rule => {
    const matched = rule.keywords.some(keyword =>
      lowerMenuName.includes(keyword.toLowerCase())
    )
    if (matched) {
      const iconInfo = [...iconConfig.common, ...iconConfig.system, ...iconConfig.business]
        .find(icon => icon.name === rule.icon)
      if (iconInfo) {
        recommendations.push({
          name: rule.icon,
          label: iconInfo.label,
          reason: rule.reason
        })
      }
    }
  })

  // 去重并限制推荐数量
  const uniqueRecommendations = recommendations.filter((item, index, self) =>
    index === self.findIndex(t => t.name === item.name)
  ).slice(0, 4)

  return uniqueRecommendations
}

const showIconRecommendation = () => {
  if (!menuForm.name) return

  const recommendations = recommendIcon(menuForm.name)
  if (recommendations.length > 0) {
    recommendedIcons.value = recommendations
    selectedRecommendIcon.value = recommendations[0].name
    iconRecommendVisible.value = true
  }
}

const applyRecommendedIcon = () => {
  if (selectedRecommendIcon.value) {
    menuForm.icon = selectedRecommendIcon.value
    iconRecommendVisible.value = false
    ElMessage.success('已应用推荐图标')
  }
}

// 获取菜单列表（树形结构）
const fetchMenuList = async () => {
  loading.value = true
  try {
    const response = await api.get('/rbac/menus/tree/')
    if (response.data.success) {
      // 使用树形结构数据
      menuList.value = response.data.data || []
    }
  } catch (error) {
    console.error('获取菜单列表失败:', error)
    menuList.value = []
  } finally {
    loading.value = false
  }
}

// 获取权限列表
const fetchPermissionList = async () => {
  try {
    const response = await api.get('/rbac/permissions/')
    if (response.data.success) {
      permissionList.value = response.data.data.results
    }
  } catch (error) {
    console.error('获取权限列表失败:', error)
  }
}

// 显示添加对话框
const showAddDialog = () => {
  dialogTitle.value = '添加菜单'
  isEdit.value = false
  dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = (menu: any) => {
  dialogTitle.value = '编辑菜单'
  isEdit.value = true
  editMenuId.value = menu.id
  
  Object.assign(menuForm, {
    name: menu.name,
    path: menu.path,
    component: menu.component || '',
    icon: menu.icon || '',
    parent: menu.parent?.id || null,
    sort_order: menu.sort_order,
    permission_ids: menu.permissions?.map((p: any) => p.id) || [],
    is_active: menu.is_active
  })
  
  dialogVisible.value = true
}

// 重置表单
const resetForm = () => {
  Object.assign(menuForm, {
    name: '',
    path: '',
    component: '',
    icon: '',
    parent: null,
    sort_order: 0,
    permission_ids: [],
    is_active: true
  })
  formRef.value?.resetFields()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        let response
        if (isEdit.value) {
          response = await api.put(`/rbac/menus/${editMenuId.value}/`, menuForm)
        } else {
          response = await api.post('/rbac/menus/', menuForm)
        }

        if (response.data.success) {
          ElMessage.success(`菜单${isEdit.value ? '更新' : '创建'}成功`)
          dialogVisible.value = false
          fetchMenuList()
          // 触发菜单更新事件，通知左侧导航栏刷新
          window.dispatchEvent(new CustomEvent('menuUpdated'))

          // 如果是新增菜单且没有选择图标，显示智能推荐
          if (!isEdit.value && !menuForm.icon && menuForm.name) {
            setTimeout(() => {
              showIconRecommendation()
            }, 500)
          }
        }
      } catch (error) {
        console.error('操作失败:', error)
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 删除菜单
const deleteMenu = async (menu: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除菜单 "${menu.name}" 吗？${menu.children && menu.children.length > 0 ? '注意：删除父菜单将同时删除所有子菜单！' : ''}`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }
    )

    // 添加删除loading状态
    const loadingInstance = ElLoading.service({
      lock: true,
      text: '正在删除菜单...',
      background: 'rgba(0, 0, 0, 0.7)'
    })

    try {
      const response = await api.delete(`/rbac/menus/${menu.id}/`)

      // 检查响应状态
      if (response.status === 204 || (response.data && response.data.success !== false)) {
        ElMessage.success('菜单删除成功')
        await fetchMenuList()
        // 触发菜单更新事件，通知左侧导航栏刷新
        window.dispatchEvent(new CustomEvent('menuUpdated'))
      } else {
        throw new Error(response.data?.message || '删除失败')
      }
    } catch (apiError: any) {
      console.error('删除菜单API错误:', apiError)

      if (apiError.response?.status === 404) {
        ElMessage.warning('菜单不存在或已被删除')
        // 菜单已不存在，刷新列表
        await fetchMenuList()
      } else if (apiError.response?.status === 403) {
        ElMessage.error('没有权限删除此菜单')
      } else if (apiError.response?.data?.message) {
        ElMessage.error(`删除失败: ${apiError.response.data.message}`)
      } else if (apiError.code === 'NETWORK_ERROR') {
        ElMessage.error('网络错误，请检查网络连接')
      } else {
        ElMessage.error('删除失败，请稍后重试')
      }

      // 发生错误时也刷新列表以确保数据同步
      await fetchMenuList()
    } finally {
      loadingInstance.close()
    }
  } catch (error: any) {
    // 用户取消删除操作
    if (error !== 'cancel') {
      console.error('删除菜单确认框错误:', error)
    }
  }
}

// 显示导航顺序调整对话框
const showOrderDialog = () => {
  // 获取当前导航菜单配置
  const currentNavigation = [
    {
      path: '/dashboard',
      meta: { title: '仪表盘', icon: 'House' }
    },
    {
      path: '/cmdb',
      meta: { title: 'CMDB资产管理', icon: 'Box' },
      children: [
        {
          path: '/cmdb/hosts',
          meta: { title: '主机管理', icon: 'Monitor' }
        },
        {
          path: '/cmdb/host-groups',
          meta: { title: '主机组管理', icon: 'Collection' }
        },
        {
          path: '/cmdb/environments',
          meta: { title: '环境管理', icon: 'Setting' }
        },
        {
          path: '/cmdb/host-types',
          meta: { title: '主机类型管理', icon: 'Cpu' }
        }
      ]
    },
    {
      path: '/database',
      meta: { title: '数据库管理', icon: 'Coin' },
      children: [
        {
          path: '/database/overview',
          meta: { title: '数据库概览', icon: 'Monitor' }
        },
        {
          path: '/database/connections',
          meta: { title: '连接管理', icon: 'Connection' }
        },
        {
          path: '/database/query',
          meta: { title: 'SQL查询', icon: 'EditPen' }
        },
        {
          path: '/database/backup',
          meta: { title: '备份管理', icon: 'Download' }
        },
        {
          path: '/database/monitoring',
          meta: { title: '性能监控', icon: 'Monitor' }
        }
      ]
    },
    {
      path: '/monitor',
      meta: { title: '运维监控', icon: 'Monitor' },
      children: [
        {
          path: '/monitor/system',
          meta: { title: '系统监控', icon: 'Cpu' }
        },
        {
          path: '/monitor/logs',
          meta: { title: '日志管理', icon: 'Document' }
        }
      ]
    },
    {
      path: '/system',
      meta: { title: '系统管理', icon: 'Setting' },
      children: [
        {
          path: '/system/users',
          meta: { title: '用户管理', icon: 'User' }
        },
        {
          path: '/system/roles',
          meta: { title: '角色管理', icon: 'UserFilled' }
        },
        {
          path: '/system/permissions',
          meta: { title: '权限管理', icon: 'Key' }
        },
        {
          path: '/system/menus',
          meta: { title: '菜单管理', icon: 'Menu' }
        }
      ]
    }
  ]

  navigationOrder.value = JSON.parse(JSON.stringify(currentNavigation))
  originalNavigationOrder.value = JSON.parse(JSON.stringify(currentNavigation))

  // 默认折叠所有有子菜单的项
  collapsedMenus.value.clear()
  currentNavigation.forEach(menu => {
    if (menu.children && menu.children.length > 0) {
      collapsedMenus.value.add(menu.path)
    }
  })

  orderDialogVisible.value = true
}

// 重置导航顺序对话框
const resetOrderDialog = () => {
  navigationOrder.value = []
  originalNavigationOrder.value = []
  collapsedMenus.value.clear()
}

// 切换子菜单折叠状态
const toggleSubmenu = (menuPath: string) => {
  if (collapsedMenus.value.has(menuPath)) {
    collapsedMenus.value.delete(menuPath)
  } else {
    collapsedMenus.value.add(menuPath)
  }
}

// 检查子菜单是否折叠
const isSubmenuCollapsed = (menuPath: string) => {
  return collapsedMenus.value.has(menuPath)
}

// 向上移动菜单
const moveUp = (index: number) => {
  if (index > 0) {
    const temp = navigationOrder.value[index]
    navigationOrder.value[index] = navigationOrder.value[index - 1]
    navigationOrder.value[index - 1] = temp
  }
}

// 向下移动菜单
const moveDown = (index: number) => {
  if (index < navigationOrder.value.length - 1) {
    const temp = navigationOrder.value[index]
    navigationOrder.value[index] = navigationOrder.value[index + 1]
    navigationOrder.value[index + 1] = temp
  }
}

// 向上移动子菜单
const moveSubMenuUp = (parentIndex: number, childIndex: number) => {
  const parent = navigationOrder.value[parentIndex]
  if (parent.children && childIndex > 0) {
    const temp = parent.children[childIndex]
    parent.children[childIndex] = parent.children[childIndex - 1]
    parent.children[childIndex - 1] = temp
  }
}

// 向下移动子菜单
const moveSubMenuDown = (parentIndex: number, childIndex: number) => {
  const parent = navigationOrder.value[parentIndex]
  if (parent.children && childIndex < parent.children.length - 1) {
    const temp = parent.children[childIndex]
    parent.children[childIndex] = parent.children[childIndex + 1]
    parent.children[childIndex + 1] = temp
  }
}

// 重置导航顺序
const resetNavigationOrder = () => {
  navigationOrder.value = JSON.parse(JSON.stringify(originalNavigationOrder.value))
  ElMessage.info('已重置为原始顺序')
}

// 保存导航顺序
const saveNavigationOrder = async () => {
  saveOrderLoading.value = true
  try {
    // 模拟保存到后端
    await new Promise(resolve => setTimeout(resolve, 1000))

    // 这里应该调用API保存新的菜单顺序
    // await api.post('/system/navigation-order', { order: navigationOrder.value })

    // 更新本地存储或状态管理
    localStorage.setItem('navigationOrder', JSON.stringify(navigationOrder.value))

    ElMessage.success('导航顺序保存成功！刷新页面后生效')
    orderDialogVisible.value = false

    // 提示用户刷新页面
    ElMessageBox.confirm(
      '导航顺序已保存，是否立即刷新页面使更改生效？',
      '提示',
      {
        confirmButtonText: '立即刷新',
        cancelButtonText: '稍后刷新',
        type: 'info'
      }
    ).then(() => {
      window.location.reload()
    }).catch(() => {
      // 用户选择稍后刷新
    })

  } catch (error) {
    ElMessage.error('保存失败，请重试')
    console.error('保存导航顺序失败:', error)
  } finally {
    saveOrderLoading.value = false
  }
}

// 恢复CMDB菜单
const restoreCMDBMenus = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要恢复CMDB菜单吗？这将创建CMDB资产管理相关的菜单项。',
      '恢复确认',
      {
        confirmButtonText: '确定恢复',
        cancelButtonText: '取消',
        type: 'info'
      }
    )

    const loadingInstance = ElLoading.service({
      lock: true,
      text: '正在恢复CMDB菜单...',
      background: 'rgba(0, 0, 0, 0.7)'
    })

    try {
      // CMDB菜单数据
      const cmdbMenuData = {
        parent: {
          name: 'CMDB资产管理',
          path: '/cmdb',
          component: 'cmdb/index',
          icon: 'Box',
          parent: null,
          sort_order: 20,
          is_active: true,
          permission_ids: []
        },
        children: [
          {
            name: '主机管理',
            path: '/cmdb/hosts',
            component: 'cmdb/HostManagement',
            icon: 'Monitor',
            sort_order: 1,
            is_active: true,
            permission_ids: []
          },
          {
            name: '主机组管理',
            path: '/cmdb/host-groups',
            component: 'cmdb/HostGroupManagement',
            icon: 'Collection',
            sort_order: 2,
            is_active: true,
            permission_ids: []
          },
          {
            name: '环境管理',
            path: '/cmdb/environments',
            component: 'cmdb/EnvironmentManagement',
            icon: 'Setting',
            sort_order: 3,
            is_active: true,
            permission_ids: []
          },
          {
            name: '主机类型管理',
            path: '/cmdb/host-types',
            component: 'cmdb/HostTypeManagement',
            icon: 'Cpu',
            sort_order: 4,
            is_active: true,
            permission_ids: []
          }
        ]
      }

      // 检查主菜单是否已存在
      const existingMenus = menuList.value
      let parentMenu = existingMenus.find(menu => menu.path === '/cmdb')

      if (!parentMenu) {
        // 创建主菜单
        const parentResponse = await api.post('/rbac/menus/', cmdbMenuData.parent)
        if (parentResponse.data.success) {
          parentMenu = parentResponse.data.data
        } else {
          throw new Error('创建CMDB主菜单失败')
        }
      }

      // 创建子菜单
      let createdCount = 0
      for (const childData of cmdbMenuData.children) {
        const existingChild = existingMenus.find(menu => menu.path === childData.path)

        if (!existingChild) {
          childData.parent = parentMenu.id
          const childResponse = await api.post('/rbac/menus/', childData)
          if (childResponse.data.success) {
            createdCount++
          }
        }
      }

      ElMessage.success(`CMDB菜单恢复成功！${parentMenu ? '主菜单已存在' : '创建了主菜单'}，创建了${createdCount}个子菜单`)

      // 刷新菜单列表
      await fetchMenuList()
      // 触发菜单更新事件
      window.dispatchEvent(new CustomEvent('menuUpdated'))

    } catch (error: any) {
      console.error('恢复CMDB菜单失败:', error)
      ElMessage.error(`恢复失败: ${error.response?.data?.message || error.message || '未知错误'}`)
    } finally {
      loadingInstance.close()
    }
  } catch (error) {
    // 用户取消操作
    if (error !== 'cancel') {
      console.error('恢复CMDB菜单确认框错误:', error)
    }
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchMenuList()
  fetchPermissionList()
})
</script>

<style scoped>
.menu-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

/* 菜单表格样式 */
.menu-tree-table {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.menu-tree-table .el-table__header) {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
}

:deep(.menu-tree-table .el-table__header th) {
  background: transparent;
  color: #495057;
  font-weight: 600;
  border-bottom: 2px solid #dee2e6;
}

:deep(.menu-tree-table .el-table__row) {
  transition: all 0.3s ease;
}

:deep(.menu-tree-table .el-table__row:hover) {
  background-color: #f8f9fa;
}

:deep(.menu-tree-table .el-table__row--level-1) {
  background-color: #fafbfc;
}

/* 菜单名称单元格样式 */
.menu-name-cell {
  display: flex;
  align-items: center;
  gap: 12px;
}

.menu-icon-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border-radius: 6px;
  background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
  border: 1px solid #90caf9;
}

.menu-icon {
  font-size: 16px;
  color: #1976d2;
}

.placeholder-icon {
  color: #9e9e9e;
}

.menu-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.menu-name {
  font-size: 14px;
  font-weight: 500;
  line-height: 1.4;
}

.menu-name.parent-menu {
  color: #1976d2;
  font-weight: 600;
}

.menu-name.child-menu {
  color: #424242;
  font-weight: 500;
}

.menu-tags {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
}

.level-tag {
  font-size: 11px;
  padding: 2px 6px;
  border-radius: 4px;
}

.children-count-tag {
  background-color: #e8f5e8;
  color: #2e7d32;
  border: 1px solid #c8e6c9;
}

/* 路径和组件文本样式 */
.path-text {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 12px;
  background: #f5f5f5;
  padding: 2px 6px;
  border-radius: 4px;
}

.component-text {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 12px;
}

/* 权限单元格样式 */
.permissions-cell {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  align-items: center;
}

.permission-tag {
  font-size: 11px;
  padding: 2px 6px;
  border-radius: 4px;
  background-color: #fff3e0;
  color: #e65100;
  border: 1px solid #ffcc02;
}

.no-permissions {
  color: #9e9e9e;
  font-size: 12px;
  font-style: italic;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 6px;
}

.action-buttons .el-button {
  padding: 4px 8px;
  font-size: 12px;
}

/* 图标输入框样式 */
.icon-input-wrapper {
  width: 100%;
}

.icon-input {
  width: 100%;
}

:deep(.icon-input .el-input__prepend) {
  padding: 0 8px;
  background: #f8f9fa;
  border-color: #dee2e6;
}

.icon-preview {
  font-size: 16px;
  color: #1976d2;
}

.icon-preview.placeholder {
  color: #9e9e9e;
}

/* 图标选择器样式 */
:deep(.icon-selector-dialog) {
  .el-dialog {
    border-radius: 12px;
  }
}

.icon-selector {
  padding: 0;
}

.icon-search {
  margin-bottom: 20px;
}

.icon-categories {
  min-height: 400px;
}

.icon-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  gap: 12px;
  padding: 16px 0;
  max-height: 350px;
  overflow-y: auto;
}

.icon-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 12px 8px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #fafafa;
}

.icon-item:hover {
  border-color: #1976d2;
  background: #e3f2fd;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(25, 118, 210, 0.2);
}

.icon-item.active {
  border-color: #1976d2;
  background: #e3f2fd;
  box-shadow: 0 0 0 2px rgba(25, 118, 210, 0.2);
}

.icon-display {
  font-size: 24px;
  color: #1976d2;
}

.icon-name {
  font-size: 11px;
  color: #666;
  text-align: center;
  line-height: 1.2;
}

/* 智能推荐对话框样式 */
:deep(.icon-recommend-dialog) {
  .el-dialog {
    border-radius: 12px;
  }
}

.icon-recommend {
  padding: 0;
}

.recommend-header {
  display: flex;
  align-items: flex-start;
  gap: 16px;
  margin-bottom: 24px;
  padding: 20px;
  background: linear-gradient(135deg, #e3f2fd 0%, #f3e5f5 100%);
  border-radius: 8px;
  border: 1px solid #e1bee7;
}

.recommend-icon {
  font-size: 32px;
  color: #9c27b0;
  margin-top: 4px;
}

.recommend-text h4 {
  margin: 0 0 8px 0;
  color: #4a148c;
  font-size: 16px;
  font-weight: 600;
}

.recommend-text p {
  margin: 0;
  color: #6a1b9a;
  font-size: 14px;
  line-height: 1.5;
}

.recommended-icons {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.recommended-icon-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #fafafa;
}

.recommended-icon-item:hover {
  border-color: #9c27b0;
  background: #f3e5f5;
  transform: translateX(4px);
}

.recommended-icon-item.selected {
  border-color: #9c27b0;
  background: #f3e5f5;
  box-shadow: 0 0 0 2px rgba(156, 39, 176, 0.2);
}

.recommended-icon-item .icon-display {
  font-size: 28px;
  color: #9c27b0;
  min-width: 32px;
}

.icon-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.icon-info .icon-name {
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

.match-reason {
  font-size: 12px;
  color: #666;
  font-style: italic;
}

/* 弹窗样式优化 */
:deep(.order-dialog) {
  .el-dialog {
    margin: auto !important;
    border-radius: 12px;
    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
    background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
    border: 1px solid rgba(120, 220, 255, 0.2);
  }

  .el-dialog__header {
    padding: 0;
    border-bottom: 1px solid rgba(120, 220, 255, 0.1);
  }

  .el-dialog__body {
    padding: 24px;
  }

  .el-dialog__footer {
    padding: 16px 24px;
    border-top: 1px solid rgba(120, 220, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
  }
}

/* 弹窗标题样式 */
.dialog-header {
  padding: 20px 24px;
  background: linear-gradient(135deg, rgba(120, 220, 255, 0.1) 0%, rgba(64, 158, 255, 0.05) 100%);
  border-radius: 12px 12px 0 0;
}

.dialog-title {
  margin: 0;
  font-size: 20px;
  font-weight: 700;
  color: #78dcff;
  display: flex;
  align-items: center;
  gap: 12px;
  text-align: center;
  justify-content: center;
}

.title-icon {
  font-size: 24px;
  color: #409eff;
}

/* 导航顺序调整样式 */
.order-management {
  padding: 0;
}

.order-tips {
  margin-bottom: 24px;
}

/* 自定义提示框 */
.custom-alert {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 16px 20px;
  background: linear-gradient(135deg, rgba(64, 158, 255, 0.08) 0%, rgba(120, 220, 255, 0.05) 100%);
  border: 1px solid rgba(64, 158, 255, 0.2);
  border-radius: 8px;
  border-left: 4px solid #409eff;
}

.alert-icon {
  color: #409eff;
  font-size: 18px;
  margin-top: 2px;
}

.alert-content {
  flex: 1;
}

.alert-title {
  font-weight: 600;
  color: #409eff;
  margin-bottom: 4px;
  font-size: 14px;
}

.alert-description {
  color: rgba(255, 255, 255, 0.8);
  font-size: 13px;
  line-height: 1.5;
}

.order-content {
  max-height: 480px;
  overflow-y: auto;
  padding-right: 8px;
}

/* 滚动条样式 */
.order-content::-webkit-scrollbar {
  width: 6px;
}

.order-content::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 3px;
}

.order-content::-webkit-scrollbar-thumb {
  background: rgba(120, 220, 255, 0.3);
  border-radius: 3px;
}

.order-content::-webkit-scrollbar-thumb:hover {
  background: rgba(120, 220, 255, 0.5);
}

/* 区域标题 */
.section-header {
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 2px solid rgba(120, 220, 255, 0.2);
}

.section-title {
  margin: 0 0 8px 0;
  color: #78dcff;
  font-weight: 700;
  font-size: 16px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.section-icon {
  color: #409eff;
  font-size: 18px;
}

.section-description {
  color: rgba(255, 255, 255, 0.6);
  font-size: 12px;
  margin-left: 26px;
}

.menu-list {
  min-height: 50px;
}

/* 拖拽相关样式 */
.draggable-list {
  min-height: 50px;
}

.drag-handle {
  cursor: grab;
  color: rgba(120, 220, 255, 0.6);
  padding: 4px;
  margin-right: 8px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.drag-handle:hover {
  color: #78dcff;
  background: rgba(120, 220, 255, 0.1);
}

.drag-handle:active {
  cursor: grabbing;
}

.submenu-drag-handle {
  cursor: grab;
  color: rgba(120, 220, 255, 0.5);
  padding: 2px;
  margin-right: 6px;
  border-radius: 3px;
  transition: all 0.3s ease;
  font-size: 12px;
}

.submenu-drag-handle:hover {
  color: rgba(120, 220, 255, 0.8);
  background: rgba(120, 220, 255, 0.08);
}

.submenu-drag-handle:active {
  cursor: grabbing;
}

/* 拖拽时的样式 */
.ghost {
  opacity: 0.5;
  background: rgba(120, 220, 255, 0.1);
  border: 2px dashed rgba(120, 220, 255, 0.3);
}

.chosen {
  transform: scale(1.02);
  box-shadow: 0 8px 24px rgba(120, 220, 255, 0.3);
}

.drag {
  transform: rotate(2deg);
  opacity: 0.8;
}

.submenu-ghost {
  opacity: 0.5;
  background: rgba(120, 220, 255, 0.05);
  border: 1px dashed rgba(120, 220, 255, 0.2);
}

.submenu-chosen {
  transform: scale(1.01);
  box-shadow: 0 4px 12px rgba(120, 220, 255, 0.2);
}

.submenu-drag {
  transform: rotate(1deg);
  opacity: 0.8;
}

/* 主菜单项样式 */
.main-menu-item {
  background: linear-gradient(135deg, rgba(120, 220, 255, 0.05) 0%, rgba(64, 158, 255, 0.02) 100%);
  border: 1px solid rgba(120, 220, 255, 0.15);
  border-radius: 10px;
  margin-bottom: 16px;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.main-menu-item:hover {
  border-color: rgba(120, 220, 255, 0.4);
  box-shadow: 0 4px 16px rgba(120, 220, 255, 0.15);
  transform: translateY(-1px);
}

.main-menu-item.has-children {
  border-left: 4px solid #409eff;
}

.main-menu-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 2px;
  background: linear-gradient(90deg, #409eff 0%, #78dcff 100%);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.main-menu-item:hover::before {
  opacity: 1;
}

.menu-item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  position: relative;
}

.menu-info {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

/* 层级指示器 */
.menu-level-indicator {
  position: relative;
  width: 4px;
  height: 24px;
  margin-right: 8px;
}

.level-line {
  width: 100%;
  height: 100%;
  background: linear-gradient(180deg, #409eff 0%, #78dcff 100%);
  border-radius: 2px;
}

/* 主菜单图标和标题 */
.main-menu-icon {
  color: #409eff;
  font-size: 20px;
}

.main-menu-title {
  font-weight: 600;
  color: #78dcff;
  font-size: 15px;
}

.children-tag {
  background: rgba(64, 158, 255, 0.1);
  color: #409eff;
  border: 1px solid rgba(64, 158, 255, 0.3);
  font-size: 11px;
}

/* 折叠按钮样式 */
.collapse-btn {
  margin-left: 8px;
  padding: 4px;
  color: rgba(120, 220, 255, 0.7);
  transition: all 0.3s ease;
}

.collapse-btn:hover {
  color: #78dcff;
  background: rgba(120, 220, 255, 0.1);
}

.menu-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.submenu-actions {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-left: auto;
}

/* 序号样式 */
.main-order {
  background: linear-gradient(135deg, #409eff 0%, #78dcff 100%);
  color: white;
  padding: 4px 10px;
  border-radius: 16px;
  font-size: 12px;
  font-weight: 700;
  min-width: 28px;
  text-align: center;
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.2);
}

.sub-order {
  background: linear-gradient(135deg, rgba(120, 220, 255, 0.8) 0%, rgba(64, 158, 255, 0.6) 100%);
  color: white;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 11px;
  font-weight: 600;
  min-width: 24px;
  text-align: center;
}

/* 子菜单样式 */
.submenu-list {
  border-top: 1px solid rgba(120, 220, 255, 0.15);
  background: linear-gradient(135deg, rgba(0, 0, 0, 0.2) 0%, rgba(16, 33, 62, 0.1) 100%);
  padding: 16px;
  margin-top: 8px;
  border-radius: 0 0 8px 8px;
}

.submenu-header {
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid rgba(120, 220, 255, 0.1);
}

.submenu-title {
  color: rgba(120, 220, 255, 0.8);
  font-size: 12px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.submenu-item {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.02) 0%, rgba(120, 220, 255, 0.01) 100%);
  border: 1px solid rgba(120, 220, 255, 0.08);
  border-radius: 6px;
  margin-bottom: 8px;
  transition: all 0.3s ease;
  position: relative;
}

.submenu-item:hover {
  border-color: rgba(120, 220, 255, 0.25);
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.04) 0%, rgba(120, 220, 255, 0.02) 100%);
  transform: translateX(4px);
}

.submenu-content {
  display: flex;
  align-items: center;
  padding: 10px 16px;
  gap: 8px;
}

.submenu-info {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

/* 子菜单层级指示器 */
.submenu-level-indicator {
  position: relative;
  width: 20px;
  height: 20px;
  margin-right: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.submenu-connector {
  position: absolute;
  left: 0;
  top: -10px;
  width: 1px;
  height: 20px;
  background: rgba(120, 220, 255, 0.3);
}

.submenu-dot {
  width: 6px;
  height: 6px;
  background: #78dcff;
  border-radius: 50%;
  border: 2px solid rgba(120, 220, 255, 0.5);
}

/* 子菜单图标和标题 */
.submenu-icon {
  color: rgba(120, 220, 255, 0.8);
  font-size: 16px;
}

.submenu-title {
  font-weight: 500;
  color: rgba(255, 255, 255, 0.9);
  font-size: 13px;
}

/* 按钮样式优化 */
.action-btn {
  padding: 6px 10px;
  min-height: 28px;
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.action-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.3);
}

.sub-action-btn {
  padding: 4px 8px;
  min-height: 24px;
  border-radius: 4px;
}

.sub-action-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 6px rgba(120, 220, 255, 0.3);
}

.action-btn .el-icon,
.sub-action-btn .el-icon {
  font-size: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  :deep(.order-dialog) .el-dialog {
    width: 95% !important;
    margin: 5vh auto !important;
  }

  .dialog-title {
    font-size: 18px;
  }

  .menu-item-content {
    padding: 12px 16px;
  }

  .menu-actions {
    gap: 6px;
  }

  .action-btn {
    padding: 4px 6px;
    min-height: 24px;
  }
}
</style>
